package com.mhs.DAO;

import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

import com.mhs.DTO.HLCDTO;
import com.mhs.DTO.MySQLiteHelper;
import com.mhs.DTO.ThuocDTO;

public class IRDAO {
	
	private SQLiteDatabase database;
	private MySQLiteHelper dbHelper;
	
	public IRDAO(Context context) {
		dbHelper = new MySQLiteHelper(context);
	}
	
	public void open() throws SQLException {
		database = dbHelper.getWritableDatabase();
	}
	
	public void close() {
		dbHelper.close();
	}
	
	public boolean saveIRtoDatabase(HLCDTO ir) {
		boolean resultInsert = false;
		database = dbHelper.getWritableDatabase();		
		String sQueryInsert = "insert into IR (IdIR, Ma, TableName, Command) values (null, " + ir.getMa() + ", '" + ir.getTable() + "', '" + ir.getCommand() + "');";
		try{
			database.execSQL(sQueryInsert);
			resultInsert = true;
		}catch(SQLException ex){
			ex.printStackTrace();
			resultInsert = false;
		}finally{
			database.close();
		}			
		return resultInsert;
	}
	
	public boolean deleteAllIR(){
		boolean checkDelete = false;
		String sQueryDel = "delete from IR;";
		database = dbHelper.getWritableDatabase();
		try{
			database.execSQL(sQueryDel);
			checkDelete = true;
		}catch(SQLException ex){
			ex.printStackTrace();
			checkDelete = false;
		}finally{
			database.close();
		}
		return checkDelete;
	}
	
	public List<HLCDTO> getAllIRwithTableName(String sTableName){
		List<HLCDTO> lstIR = new ArrayList<HLCDTO>();
		try{
		String sQuery = "select IdIR, Ma, TableName, Command from IR where TableName = '" + sTableName + "';";
		database = dbHelper.getReadableDatabase();
		Cursor cursor = database.rawQuery(sQuery, new String [] {});
		if(cursor.getCount() == 0){
			lstIR = null;
		}else{
			cursor.moveToFirst();
			while (!cursor.isAfterLast()) {
				HLCDTO ir = new HLCDTO();
				ir.setMa(String.valueOf(cursor.getInt(1)));
				ir.setTable(cursor.getString(2));
				ir.setCommand(cursor.getString(3));
				lstIR.add(ir);
				cursor.moveToNext();
			}
			cursor.close();
		}
		}catch(SQLException ex){
			ex.printStackTrace();
			lstIR = new ArrayList<HLCDTO>();
		}finally{
			database.close();
		}
		return lstIR;
	}
}
